package nongchang.kuaijiecaifu.com.ncapp_android.util.validator;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.IdRes;
import android.view.View;

import com.mobsandgeeks.saripaar.ValidationError;
import com.mobsandgeeks.saripaar.Validator;

import java.text.ParseException;
import java.util.List;

import ezy.lite.util.UI;

public class DefaultValidator {

    private Validator mValidator;
    private OnValidationSucceeded onSuccess;
    private OnValidationFailed onFailed;

    protected View mClicked;

    public DefaultValidator() {

    }
    public DefaultValidator(Object o) {
        init(o);
    }

    protected void init(Object o) {
        mValidator = new Validator(o);
        mValidator.setValidationMode(Validator.Mode.IMMEDIATE);
        mValidator.setValidationListener(new Validator.ValidationListener() {
            @Override
            public void onValidationSucceeded() {
                if (onSuccess == null) {
                    return;
                }
                try {
                    onSuccess.onValidateSuccess();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onValidationFailed(List<ValidationError> errors) {
                if (onSuccess == null) {
                    return;
                }
                Context context = errors.get(0).getView().getContext();
                UI.showToast(context, errors.get(0).getCollatedErrorMessage(context));
            }
        });

    }

    public void validate() {
        mValidator.validate();
    }

    public DefaultValidator clicked(View view) {
        mClicked = view;
        mClicked.setOnClickListener(v -> mValidator.validate());
        return this;
    }
    public DefaultValidator clicked(Activity context, @IdRes int resId) {
        mClicked = context.findViewById(resId);
        mClicked.setOnClickListener(v -> mValidator.validate());
        return this;
    }
    public DefaultValidator succeeded(OnValidationSucceeded l) {
        onSuccess = l;
        return this;
    }
    public DefaultValidator failed(OnValidationFailed l) {
        onFailed = l;
        return this;
    }
}